import { Component, ChangeDetectionStrategy, Input, NgZone, ChangeDetectorRef } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';

/**
 * 售后维修返修率仪表盘
 */
@Component({
  selector: 'prod-repair-rate',
  templateUrl: './repair-rate-gauge.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class RepairRateGaugeComponent {
  @Input()
  title = '';
  _codeName = null;
  @Input()
  set codeName(val) {
    if (val) {
      this._codeName = val;
      this.attachData(this._codeName);
    }
  }
  loading = false;
  time = null;
  percent = 0;
  color = '#2f9cff';

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.percent = 0;
      this.loading = true;
      this.cdr.detectChanges();
    });
    this.http.get(`/cf/report/prod/repairrate/${codeName}`).subscribe(res => {
      ngZone.run(() => {
        this.time = new Date();
        if (res.data) {
          if (res.data.SC === 0) {
            this.percent = 0;
          } else {
            this.percent = parseInt(Math.round((res.data.RC / res.data.SC) * 100).toString(), 10);
            if (this.percent <= 20) {
              this.color = '#2f9cff';
            } else if (this.percent <= 40 && this.percent >= 21) {
              this.color = '#4be49b';
            } else if (this.percent <= 60 && this.percent >= 41) {
              this.color = '#efde41';
            } else {
              this.color = '#f50';
            }
          }
        }
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }

  couponFormat(val: any) {
    switch (parseInt(val, 10)) {
      case 20:
        return '优';
      case 40:
        return '良';
      case 60:
        return '中';
      case 80:
        return '差';
      default:
        return '';
    }
  }
}
